package com.bitejiuyeke.job_publish.service.impl;

import com.bitejiuyeke.job_publish.common.AppResult;
import com.bitejiuyeke.job_publish.dao.CollegeMapper;
import com.bitejiuyeke.job_publish.exception.ApplicationException;
import com.bitejiuyeke.job_publish.model.College;
import com.bitejiuyeke.job_publish.service.ICollegeService;
import com.bitejiuyeke.job_publish.utils.JsonUtils;
import com.bitejiuyeke.job_publish.utils.RedisUtils;
import com.bitejiuyeke.job_publish.utils.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 院系相关业务接口实现类
 *
 * @Author 比特就业课
 */
@Slf4j
@Service
public class CollegeServiceImpl implements ICollegeService {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private CollegeMapper mapper;

    private final String KEY_COLLEGES_ALL_INFO = "COLLEGE:ALL:INFO";

    private final String KEY_COLLEGES = "COLLEGES";

    @Override
    public List<College> selectAll() {
        List<College> result = null;
        // 先从缓存中获取
        String content = (String) redisUtils.get(KEY_COLLEGES);
        if (!StringUtils.isEmpty(content)) {
            result = JsonUtils.readListValue(content, College.class);
            // 日志
            log.info("从缓存中获取了所以院系信息");
            return result;
        }
        // 缓存中没有从数据库中查询
        result = mapper.selectAll();
        if (result == null || result.size() == 0) {
            log.error("院系数据未初始化.");
            throw new ApplicationException(AppResult.failed("院系数据未初始化."));
        }
        // 加入缓存
        redisUtils.set(KEY_COLLEGES, JsonUtils.writeValueAsString(result));
        // 日志
        log.info("从数据库中获取了所以院系信息");
        // 返回结果
        return result;
    }

    @Override
    public List<College> selectAllInfo() {
        List<College> result = null;
        // 先从缓存中获取
        String content = (String) redisUtils.get(KEY_COLLEGES_ALL_INFO);
        if (!StringUtils.isEmpty(content)) {
            result = JsonUtils.readListValue(content, College.class);
            // 日志
            log.info("从缓存中获取了院系详细信息");
            return result;
        }
        // 从数据库中查询
        result = mapper.selectAllInfo();
        if (result == null || result.size() == 0) {
            log.error("院系数据未初始化.");
            throw new ApplicationException(AppResult.failed("院系数据未初始化."));
        }
        // 写入缓存
        redisUtils.set(KEY_COLLEGES_ALL_INFO, JsonUtils.writeValueAsString(result));
        // 日志
        log.info("从查询库中获取了院系详细信息");
        return result;
    }
}
